
package com.espier.t9keyboard;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ToneGenerator;
import android.os.PatternMatcher;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class SearchControl {
    private Context mContext;
    private Map<Character, Character[]> t9Map = new HashMap<Character, Character[]>();
    private Map<Character, String[]> pinyinMap = new HashMap<Character, String[]>();
    private Map<Character, String[]> t9pinyinMap = new HashMap<Character, String[]>();
    private static SearchControl mInstance;

    private SearchControl(Context c) {
        mContext = c;

        t9Map.put('1', null);
        t9Map.put('2', SearchContant.t9_2);
        t9Map.put('3', SearchContant.t9_3);

        t9Map.put('4', SearchContant.t9_4);
        t9Map.put('5', SearchContant.t9_5);
        t9Map.put('6', SearchContant.t9_6);

        t9Map.put('7', SearchContant.t9_7);
        t9Map.put('8', SearchContant.t9_8);
        t9Map.put('9', SearchContant.t9_9);

        t9Map.put('*', null);
        t9Map.put('0', null);
        t9Map.put('#', null);

        pinyinMap.put('a', SearchContant.t9_a);
        pinyinMap.put('b', SearchContant.t9_b);
        pinyinMap.put('c', SearchContant.t9_c);
        pinyinMap.put('d', SearchContant.t9_d);
        pinyinMap.put('e', SearchContant.t9_e);

        pinyinMap.put('f', SearchContant.t9_f);
        pinyinMap.put('g', SearchContant.t9_g);
        pinyinMap.put('h', SearchContant.t9_h);
        pinyinMap.put('i', SearchContant.t9_i);
        pinyinMap.put('j', SearchContant.t9_j);

        pinyinMap.put('k', SearchContant.t9_k);
        pinyinMap.put('l', SearchContant.t9_l);
        pinyinMap.put('m', SearchContant.t9_m);
        pinyinMap.put('n', SearchContant.t9_n);
        pinyinMap.put('o', SearchContant.t9_o);

        pinyinMap.put('p', SearchContant.t9_p);
        pinyinMap.put('q', SearchContant.t9_q);
        pinyinMap.put('r', SearchContant.t9_r);
        pinyinMap.put('s', SearchContant.t9_s);
        pinyinMap.put('t', SearchContant.t9_t);

        pinyinMap.put('u', SearchContant.t9_u);
        pinyinMap.put('v', SearchContant.t9_v);
        pinyinMap.put('w', SearchContant.t9_w);
        pinyinMap.put('x', SearchContant.t9_x);
        pinyinMap.put('y', SearchContant.t9_y);

        pinyinMap.put('z', SearchContant.t9_z);

        t9pinyinMap.put('1', null);
        t9pinyinMap.put('2', SearchContant.pinyin2);
        t9pinyinMap.put('3', SearchContant.pinyin3);

        t9pinyinMap.put('4', SearchContant.pinyin4);
        t9pinyinMap.put('5', SearchContant.pinyin5);
        t9pinyinMap.put('6', SearchContant.pinyin6);

        t9pinyinMap.put('7', SearchContant.pinyin7);
        t9pinyinMap.put('8', SearchContant.pinyin8);
        t9pinyinMap.put('9', SearchContant.pinyin9);

        t9pinyinMap.put('*', null);
        t9pinyinMap.put('0', null);
        t9pinyinMap.put('#', null);

    }

    public static SearchControl getInstance(Context c) {
        if (mInstance != null) {
            return mInstance;
        } else {
            mInstance = new SearchControl(c);
            return mInstance;
        }
    }

    private List<ContactPerson> mContactsList;
    private StringBuilder searchBuilder = new StringBuilder();
    private List<KeyWord> keyWordList;
    private Map<Integer, List<ContactPerson>> stateMap = new HashMap<Integer, List<ContactPerson>>();
    private Map<String, ContactPerson> contactsMap ;
    public void setKeyCode(int code) {
        switch (code) {
            case KeyEvent.KEYCODE_1: {
                addSearchKey('1');
                return;
            }
            case KeyEvent.KEYCODE_2: {
                addSearchKey('2');
                return;
            }
            case KeyEvent.KEYCODE_3: {
                addSearchKey('3');
                return;
            }
            case KeyEvent.KEYCODE_4: {
                addSearchKey('3');
                return;
            }
            case KeyEvent.KEYCODE_5: {
                addSearchKey('5');
                return;
            }
            case KeyEvent.KEYCODE_6: {
                addSearchKey('6');
                return;
            }
            case KeyEvent.KEYCODE_7: {
                addSearchKey('7');
                return;
            }
            case KeyEvent.KEYCODE_8: {
                addSearchKey('8');
                return;
            }
            case KeyEvent.KEYCODE_9: {
                addSearchKey('9');
                return;
            }
            case KeyEvent.KEYCODE_0: {
                addSearchKey('0');
                return;
            }
            case KeyEvent.KEYCODE_STAR: {
                addSearchKey('*');
                return;
            }
            case KeyEvent.KEYCODE_POUND: {
                addSearchKey('#');
                return;
            }
            case KeyEvent.KEYCODE_DEL: {
                delSearchKey();
                return;
            }
        }
    }

    public void addSearchKey(char keyChar) {

        if (isFirstSearch()) {
            String[] tempStr = t9pinyinMap.get(keyChar);
            searchPinyinContactsFirst(mContext, tempStr);
        } else {
            Character[] tempStr = t9Map.get(keyChar);
            mContactsList = searchPinyinContactsCommon(mContext, tempStr);
        }
        searchBuilder.append(keyChar);
        stateMap.put(searchBuilder.length(), mContactsList);
    }

    public void delSearchKey() {
        searchBuilder.deleteCharAt(searchBuilder.length() - 1);
        if (searchBuilder.length() == 0) {
            mContactsList = null;
            stateMap.clear();
        } else {
            mContactsList = stateMap.get(searchBuilder.length());
        }
    }

    public boolean isFirstSearch() {
        return searchBuilder.length() == 0;
    }

    public List<ContactPerson> getContanctsList() {
        return mContactsList;

    }

    public void searchPinyinContactsFirst(Context context, String[] strs) {
        Cursor cur = null;
        Map<String, KeyWord> keyWordMap = new HashMap<String, KeyWord>();
        contactsMap=new HashMap<String, ContactPerson>();
        try {
            String[] contacts_projection = {
                    ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER
                    , ContactsContract.Contacts.PHOTO_ID
                    , ContactsContract.Contacts.STARRED, ContactsContract.Contacts.CUSTOM_RINGTONE
                    , ContactsContract.Contacts.SORT_KEY_PRIMARY,
                    ContactsContract.Contacts.LOOKUP_KEY
            };
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < strs.length; i++) {
                builder.append(" or sort_key" + " like '%" + strs[i] + " %'");
            }
            builder.delete(0, 3);
            cur = context.getContentResolver()
                    .query(ContactsContract.Contacts.CONTENT_URI,
                            contacts_projection, builder.toString(), null,
                            null);

            while (cur.moveToNext()) {
                ContactPerson person = new ContactPerson(context);
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                int hasNumber = cur.getInt(cur
                        .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String photo_id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
                int starred = cur.getInt(cur
                        .getColumnIndex(ContactsContract.Contacts.STARRED));
                String custom_ringtone = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.CUSTOM_RINGTONE));
                String sort_key = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.SORT_KEY_PRIMARY));

                for (int i = 0; i < strs.length; i++) {
                    if (sort_key.toUpperCase().contains((strs[i] + " ").toUpperCase())) {
                        if (!keyWordMap.containsKey(strs[i])) {
                            keyWordMap.put(strs[i], new KeyWord(new String[] {
                                    strs[i]
                                }));
                        }
                    }
                }

                String lookup = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                person.setContactId(id);
                person.setName(name);
                person.setPhotoId(photo_id);
                person.setSortKey(sort_key);
                person.setLookup(lookup);
                contactsMap.put(person.getContactId(), person);
                Log.e("lmf", cur.getCount() + "=======111111111===>>>>>=" + id + ":" + name + ":"
                        + sort_key
                        + ":");
            }
            keyWordList = new ArrayList<KeyWord>(keyWordMap.values());
            Log.e("lmf", "========11111111=<<<<<<<<<<<<<<<<<<<>>>>>=" + keyWordList.size());
        } finally {
            if (cur != null) {
                cur.close();
            }
        }
    }

    public List<ContactPerson> searchPinyinContactsCommon(Context context, Character[] chars) {
        Cursor cur = null;
        Map<String, KeyWord> keyWordMap = new HashMap<String, KeyWord>();
        try {
            List<ContactPerson> personList = new ArrayList<ContactPerson>();

            String[] contacts_projection = {
                    ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER
                    , ContactsContract.Contacts.PHOTO_ID
                    , ContactsContract.Contacts.STARRED, ContactsContract.Contacts.CUSTOM_RINGTONE
                    , ContactsContract.Contacts.SORT_KEY_PRIMARY,
                    ContactsContract.Contacts.LOOKUP_KEY
            };
            StringBuilder builder = new StringBuilder();
            Log.e("lmf", "=======2222222===========");
            for (KeyWord key : keyWordList) {
                Log.e("lmf", "=======2222222=====key.word======" + key.toString());
                for (int i = 0; i < chars.length; i++) {
                    builder.append(" or sort_key" + " like '%" + key.getSelection() + "% "
                            + chars[i] + "%'");
                }
            }
            builder.delete(0, 3);
            Log.e("lmf", "=======2222222===========" + builder.toString());
            cur = context.getContentResolver()
                    .query(ContactsContract.Contacts.CONTENT_URI,
                            contacts_projection, builder.toString(), null,
                            null);

            while (cur.moveToNext()) {
                ContactPerson person = new ContactPerson(context);
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                int hasNumber = cur.getInt(cur
                        .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String photo_id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
                int starred = cur.getInt(cur
                        .getColumnIndex(ContactsContract.Contacts.STARRED));
                String custom_ringtone = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.CUSTOM_RINGTONE));
                String sort_key = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.SORT_KEY_PRIMARY));

                for (KeyWord key : keyWordList) {
                    for (int i = 0; i < chars.length; i++) {
                        if (Pattern.matches((key.getRegex() + " " + chars[i] + ".*").toUpperCase(),
                                sort_key.toUpperCase())) {
                            KeyWord newKey = new KeyWord(key.getKey(), String.valueOf(chars[i]));
                            keyWordMap.put(newKey.toString(), newKey);
                        }

                    }
                }

                String lookup = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                person.setContactId(id);
                person.setName(name);
                person.setPhotoId(photo_id);
                person.setSortKey(sort_key);
                person.setLookup(lookup);

                Log.e("lmf", cur.getCount() + "=========22222222=>>>>>=" + id + ":" + name + ":"
                        + sort_key);
            }
            keyWordList = new ArrayList<KeyWord>(keyWordMap.values());
            Log.e("lmf", "=========<<<<<<<<<<<<<<<222222222<<<>>>>>=" + keyWordList.size());
            return personList;
        } finally {
            if (cur != null) {
                cur.close();
            }
        }
    }

    List<String> listStrings = new ArrayList<String>();

}
